package com.yimi.yinhepda;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.util.ArraySet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.pda.ym.updateApk.UpdateApk;
import com.yimi.yinhepda.JPush.TagAliasOperatorHelper;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.callbacks.OnClickCallBack;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CheckBalanceTableDao;
import com.yimi.yinhepda.db.dao.ForklifStatisticsTableDao;
import com.yimi.yinhepda.db.dao.LoadUnloadGroupTableDao;
import com.yimi.yinhepda.db.dao.MyMessageDao;
import com.yimi.yinhepda.db.dao.SortScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.dao.UserReadMessageDao;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.table.SortScanTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.downLoadBaseData.DownLoadBaseData;
import com.yimi.yinhepda.entity.bean.CurrentSpaceEntity;
import com.yimi.yinhepda.entity.message.MyMessageBean;
import com.yimi.yinhepda.entity.message.UserReadMessageBean;
import com.yimi.yinhepda.net.QueryPlaceNetRequest;
import com.yimi.yinhepda.service.BootBroadcastReceiver;
import com.yimi.yinhepda.service.CommonService;
import com.pda.ym.utils.ActivityStack;
import com.pda.ym.utils.AppInfoHelper;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.uce.commom.util.LogUtil;
import com.yimi.yinhepda.utils.ScanToolControlUtil;
import com.yimi.yinhepda.utils.ThreadPoolUtils;
import com.yimi.yinhepda.views.check_balance.CheckBalanceActivity;
import com.yimi.yinhepda.views.createPackage_module.CreatePackageMangerActivity;
import com.yimi.yinhepda.views.dispatch_module.DispatchManageActivity;
import com.yimi.yinhepda.views.exceptionsUpload_module.ExceptionUploadActivity;
import com.yimi.yinhepda.views.lan_huo_scan.LanHuoScanActivity;
import com.yimi.yinhepda.views.load_module.LoadFunctionActivity;
import com.yimi.yinhepda.views.message.MessageListActivity;
import com.yimi.yinhepda.views.moveStock_module.MoveStockActivity;
import com.yimi.yinhepda.views.offline.OffLineOperatorListActivity;
import com.yimi.yinhepda.views.offline.load.OffLineLoadUtil;
import com.yimi.yinhepda.views.offline.unload.OffLineUnLoadUtil;
import com.yimi.yinhepda.views.seal_module.SealManagerActivity;
import com.yimi.yinhepda.views.setting_module.SettingActivity;
import com.yimi.yinhepda.views.sign_manager.SelectBreakCardTypeActivity;
import com.yimi.yinhepda.views.sort_module.SortingSelectActivity;
import com.yimi.yinhepda.views.stockCheck_module.StockCheckActivity;
import com.yimi.yinhepda.views.unload_module.UnloadActivity;

import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import cn.jpush.android.api.JPushInterface;

import static com.yimi.yinhepda.JPush.TagAliasOperatorHelper.ACTION_SET;

/**
 * @author 000432
 */
public class MainActivity extends BaseActivity {
    /**
     * 是否退出线程
     */
    private boolean isExit = false;
    /**
     * 消息按钮
     */
    private ImageView mIvMessage;
    /**
     * 消息未读标志
     */
    private TextView mUnReadTag;
    private String userCode;
    private Button btnSignManager;
    private Button btnYiku;
    /**
     * 离线数据
     */
    private Button offlineTempData;
    /**
     * 部门类型
     */
    private int mDeptType;
    /**
     * 揽货扫描
     */
    private Button btnLanhuo;
    /**
     * 当前部门名称
     */
    private TextView tvCurrentDeptName;
    private Intent intentService;
    private MyServiceConnection connService;
    public static CommonService.IService iService;
    public static Handler handler;
    public static final int READ_MESSAGE_TAG_STATUS = 101;
    private static final int REQUEST_EXTERNAL_STORAGE = 102;
    public static final int UPDATE_OFFLINE_DATA_NUM = 103;
    private BootBroadcastReceiver receiver;
    private AlarmManager alarmManager;
    private PendingIntent pendingIntent;

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //拿到在服务里面实现了IService接口的Binder对象
            iService = (CommonService.IService) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //8.0以上由于限制了静态广播，所以动态设置广播
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            receiver = new BootBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(BootBroadcastReceiver.ACTION_BOOT);
            filter.addAction(Constants.ACTION_ONRESUME);
            filter.addAction(BootBroadcastReceiver.ACTION_DATE_CHANGED);
            filter.addAction(BootBroadcastReceiver.ACTION_TIME_CHANGED);
            filter.addAction(BootBroadcastReceiver.ACTION_TIMEZONE_CHANGED);
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            registerReceiver(receiver, filter);
        }

        startCheckBalanceService();
        initView();
        initDate();
        setHandler();
        initAlarmBroadcast();

        setTimeZone("GMT+08:00");
    }


    public void setTimeZone(String timeZone) {
        final Calendar now = Calendar.getInstance();
        TimeZone tz = TimeZone.getTimeZone(timeZone);
        now.setTimeZone(tz);
    }

    private void initAlarmBroadcast() {
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();

        calendar.setTimeInMillis(System.currentTimeMillis());

        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));

        calendar.add(Calendar.SECOND, 1);

        Intent intent = new Intent("intent_alarm_log");

        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

        long intervalMillis = 150000;// 3秒,此设置无用，时间间隔误差60s

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervalMillis, pendingIntent);
    }

    /**
     * 启动绑定和启动复秤检查服务
     */
    private void startCheckBalanceService() {
        connService = new MyServiceConnection();
        intentService = new Intent(this, CommonService.class);
        this.bindService(intentService, connService, BIND_AUTO_CREATE);
    }

    /**
     * 停止绑定和停止复秤检查服务
     */
    private void stopCheckBalanceService() {
        stopService(new Intent(this, CommonService.class));
        if (connService != null) {
            this.unbindService(connService);
            connService = null;
        }
    }

    /**
     * 线程池执行耗时操作
     */
    private class UploadRunnable implements Runnable {
        @Override
        public void run() {
            try {
                //清除本地15天前的数据
                DbHelper.deleteData();
                //删除已上传的分拣数据
                SortScanTableDao mSortScanTableDao = new SortScanTableDao();
                List<SortScanTable> list = mSortScanTableDao.getUploaded();
                mSortScanTableDao.delete(list);
                //初始化车牌数据
                Common.initCarPalteData(MainActivity.this);
                //登录后清除复秤检查数据
                new CheckBalanceTableDao().deleteAll();
                //登录后清除装卸组信息
                new LoadUnloadGroupTableDao().deleteAll();
                //登录后清除叉车分货统计数据
                new ForklifStatisticsTableDao().deleteAll();
                //设置卸车组标志为未设置
                sharedPreferUtil.setBooleanValue(Common.HAS_UNLOAD_GROUP, false);
                //上传离线装车数据
                OffLineLoadUtil.uploadOfflineLoadData();
                //上传离线卸车数据
                OffLineUnLoadUtil.uploadOfflineLoadData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void initView() {
        findViewById(R.id.btn_load).setOnClickListener(this);
        findViewById(R.id.btn_unload).setOnClickListener(this);
        findViewById(R.id.btn_repertory_check).setOnClickListener(this);
        findViewById(R.id.btn_sorting).setOnClickListener(this);
        findViewById(R.id.btn_upload_exception).setOnClickListener(this);
        findViewById(R.id.btn_build_package_management).setOnClickListener(this);
        findViewById(R.id.btn_dispatch).setOnClickListener(this);
        findViewById(R.id.btn_fengcun_management).setOnClickListener(this);
        findViewById(R.id.btn_check_balance).setOnClickListener(this);
        findViewById(R.id.btn_system_setting).setOnClickListener(this);
        findViewById(R.id.btn_offline_operator).setOnClickListener(this);
        btnYiku = findViewById(R.id.btn_yiKuDaoHuo);
        btnYiku.setOnClickListener(this);
        offlineTempData = findViewById(R.id.tv_offline_temp_save);
        btnSignManager = findViewById(R.id.btn_sign_manager);
        btnSignManager.setOnClickListener(this);
        mIvMessage = findViewById(R.id.main_iv_message);
        mIvMessage.setOnClickListener(this);
        mUnReadTag = findViewById(R.id.message_iv_unread_tag);
        btnLanhuo = findViewById(R.id.btn_lanHuoScan);
        btnLanhuo.setOnClickListener(this);
        tvCurrentDeptName = findViewById(R.id.tv_currentDeptName);
    }

    @Override
    public String getPageName() {
        return getString(R.string.page_main);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //请求读写权限
        requestExternalStoragePermission();

        //打印分辨率
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        JPushInterface.resumePush(getApplicationContext());
        //更新已读消息标志
        setReadMessageTagStatus();
        //离线操作数量
        showOfflineDataNum();
    }

    public void initDate() {
        tvCurrentDeptName.setText(sharedPreferUtil.getValue(Common.DEPT_NAME));
        mDeptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        if (mDeptType == 5 || mDeptType == 6) {
            //分拨屏蔽签到管理功能
            btnSignManager.setEnabled(false);
            btnLanhuo.setVisibility(View.GONE);
        } else {
            btnSignManager.setEnabled(true);
            btnLanhuo.setVisibility(View.VISIBLE);
        }

        userCode = sharedPreferUtil.getValue(Common.USER_CODE);

        //JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        JPushInterface.resumePush(getApplicationContext());
        //设置消息推送别名和tag
        setMessageAliasAndTag();

        //初始化扫描工具
        initScanTool();

        //判断是否需要下载数据
        if (!sharedPreferUtil.getOfflineMode()) {
            //下载基础数据,首次主界面下载，第二次在service中静默下载
            if (sharedPreferUtil.getServerIpHaveChanged()) {
                if (BuildConfig.DEBUG) {
//                    new DownLoadBaseData(this, true).downloadBaseData();
                } else {
                    new DownLoadBaseData(this, true).downloadBaseData();
                }
            }
        }

        Common.queryMergeLoadScanCreateTask();

        //设置版本为当前程序版本
        //因为程序第一次进入main的时候删除了已经下载的版本
        sharedPreferUtil.setValue(Constants.VERSION, AppInfoHelper.getAppVersion(this) + "");

        ThreadPoolUtils.execute(new UploadRunnable());
    }

    /**
     * 离线操作数量
     */
    private synchronized void showOfflineDataNum() {
        UnloadTaskTableDao unloadTaskTableDao = new UnloadTaskTableDao();
        int offlineCount = 0;
        List<UnloadTaskTable> loadTaskList = new UnloadTaskTableDao().findByOperTypeCode1(userCode, sharedPreferUtil.getDeptCode());
        if (loadTaskList != null) {
            for (UnloadTaskTable item : loadTaskList) {
                if (item.getOfflineTaskNo() != null && item.getIsUpload() != 1 && item.getOfflineTaskNo().startsWith("Z")) {
                    offlineCount++;
                }
            }
        }
        List<UnloadTaskTable> unloadTaskList = unloadTaskTableDao.findByOperTypeCode2(userCode, sharedPreferUtil.getDeptCode());
        if (unloadTaskList != null) {
            for (UnloadTaskTable item : unloadTaskList) {
                if (item.getOfflineTaskNo() != null && item.getOfflineTaskNo().startsWith("X") && item.getIsUpload() != 1) {
                    offlineCount++;
                }
            }
        }

        if (offlineCount == 0) {
            offlineTempData.setText("");
            offlineTempData.setVisibility(View.GONE);
        } else {
            offlineTempData.setText(offlineCount + "");
            offlineTempData.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 请求读写权限县
     */
    private void requestExternalStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permission = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission == PackageManager.PERMISSION_GRANTED) {
                //检测更新版本
                UpdateApk.getInstance(this, sharedPreferUtil).upgrade();
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_EXTERNAL_STORAGE);
            }
        } else {
            //检测更新版本
            UpdateApk.getInstance(this, sharedPreferUtil).upgrade();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                requestExternalStoragePermission();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                //请求SD卡读写权限
                if ((grantResults.length > 0) && (
                        grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    //检测更新版本
                    UpdateApk.setNull();
                    UpdateApk.getInstance(this, sharedPreferUtil).upgrade();
                } else {
                    Common.showPermissionDialog(this, "程序需要打开读写存储权限，是否打开！", REQUEST_EXTERNAL_STORAGE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        //退出上传离线状态日志
        Common.uploadPdaManagerLogInfo(this, 2);
        //退出线程
        isExit = true;
        handler = null;
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        if (alarmManager != null) {
            alarmManager.cancel(pendingIntent);
        }
        stopCheckBalanceService();
        ActivityStack.getInstance().exit();
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        //退出线程
        isExit = true;
        JPushInterface.clearAllNotifications(getApplicationContext());
        JPushInterface.stopPush(getApplicationContext());
    }

    public void initScanTool() {
        //设置广播名称和条码键值
        ScanToolControlUtil.getInstance().setBroadCastName(this);
        //设置接收条码的结束符
        ScanToolControlUtil.getInstance().setBroadCastEndChar(this);
        //设置扫描声音
        ScanToolControlUtil.getInstance().setScanSound(this);
        //设置开机自启动
        ScanToolControlUtil.getInstance().setBootStart(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_load:
                //出发装车
                toActivity(LoadFunctionActivity.class);
                break;
            case R.id.btn_unload:
                //到达卸车
                toActivity(UnloadActivity.class);
                break;
            case R.id.btn_repertory_check:
                if (sharedPreferUtil.getOfflineMode()) {
                    showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                //库存盘点
                toActivity(StockCheckActivity.class);
                break;
            case R.id.btn_sorting:
                //分拣管理
                if (sharedPreferUtil.getOfflineMode()) {
                    showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                toActivity(SortingSelectActivity.class);
                break;
            case R.id.btn_upload_exception:
                if (sharedPreferUtil.getOfflineMode()) {
                    showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                //异常上报
                toActivity(ExceptionUploadActivity.class);
                break;
            case R.id.btn_build_package_management:
                if (sharedPreferUtil.getOfflineMode()) {
                    showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                //建包管理
                toActivity(CreatePackageMangerActivity.class);
                break;
            case R.id.btn_dispatch:
                if (sharedPreferUtil.getOfflineMode()) {
                    showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                //配送管理
                toActivity(DispatchManageActivity.class);
                break;
            case R.id.btn_fengcun_management:
                if (sharedPreferUtil.getOfflineMode()) {
                    showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                //封签管理
                toActivity(SealManagerActivity.class);
                break;
            case R.id.btn_check_balance:
                if (sharedPreferUtil.getOfflineMode()) {
                    showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                //复秤检查
                Intent intent = new Intent(this, CheckBalanceActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("iService", iService);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.btn_system_setting:
                //系统设置
                toActivity(SettingActivity.class);
                break;
            case R.id.main_iv_message:
                //推送消息列表
                toActivity(MessageListActivity.class);
                break;
            case R.id.btn_sign_manager:
                //签到管理
                toActivity(SelectBreakCardTypeActivity.class);
                break;
            case R.id.btn_offline_operator:
                //离线操作
                toActivity(OffLineOperatorListActivity.class);
                break;
            case R.id.btn_yiKuDaoHuo:
                //移库倒货按钮
                queryPlaceRequest();
                break;
            case R.id.btn_lanHuoScan:
                //揽货扫描
                toActivity(LanHuoScanActivity.class);
                break;
            default:
                break;
        }
    }

    /**
     * 查询场地
     */
    private void queryPlaceRequest() {
        showPgDlg("请求数据中...");
        final QueryPlaceNetRequest placeNetRequest = new QueryPlaceNetRequest().setDeptCode(sharedPreferUtil.getDeptCode());
        //查询该部门是否启用移库倒货功能
        placeNetRequest.queryDataDict(new UICallBack() {
            @Override
            public void onError(String msg) {
                dismissPgDlg();
                if (msg != null) {
                    showToast(msg);
                }
            }

            @Override
            public void onSuccess(Object obj) {
                //启用移库倒货功能，则查询场地
                placeNetRequest.querySpaceByDept(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        if (msg != null) {
                            showToast(msg);
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        List<CurrentSpaceEntity> dataList = (List<CurrentSpaceEntity>) obj;
                        placeNetRequest.showSelectSpaceDialog(MainActivity.this, dataList, new OnClickCallBack() {
                            @Override
                            public void onCancle() {
                            }

                            @Override
                            public void onSure(Object obj, Object dialog) {
                                CurrentSpaceEntity currentSpaceEntity = (CurrentSpaceEntity) obj;
                                if (currentSpaceEntity != null && currentSpaceEntity.isCheck()) {
                                    dismissPgDlg();
                                    Dialog mDialog = (Dialog) dialog;
                                    mDialog.dismiss();
                                    //保存当前所在场地
                                    sharedPreferUtil.setValue(Common.PLACE_CODE, currentSpaceEntity.getPlaceCode());
                                    sharedPreferUtil.setValue(Common.PLACE_NAME, currentSpaceEntity.getPlaceName());
                                    toActivity(MoveStockActivity.class);
                                } else {
                                    showToast("请选择当前所在场地！");
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void setHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case READ_MESSAGE_TAG_STATUS:
                        setReadMessageTagStatus();
                        break;
                    case UPDATE_OFFLINE_DATA_NUM:
                        //显示离线操作数量
                        showOfflineDataNum();
                        break;
                    default:
                        break;
                }
            }
        };
    }

    /**
     * 设置消息别名和tag
     */
    private void setMessageAliasAndTag() {
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = ACTION_SET;
        tagAliasBean.alias = userCode;
        tagAliasBean.tags = new ArraySet<String>();
        tagAliasBean.tags.add(sharedPreferUtil.getDeptCode());
        tagAliasBean.tags.add(sharedPreferUtil.getCompanyCode());
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), TagAliasOperatorHelper.sequence++, tagAliasBean);
        LogUtil.e(tagAliasBean.toString());
    }

    /**
     * 设置消息未读状态
     */
    private synchronized void setReadMessageTagStatus() {
        //所有消息
        List<MyMessageBean> myMessageBeanList = null;
        myMessageBeanList = new MyMessageDao().findAll();
        String operator = sharedPreferUtil.getValue(Common.USER_CODE);
        //用户已读消息
        List<UserReadMessageBean> userReadMessageBeanList = new UserReadMessageDao().getReadMessageByOperator(operator);
        if (myMessageBeanList != null) {
            if (userReadMessageBeanList != null) {
                if (userReadMessageBeanList.size() >= myMessageBeanList.size()) {
                    //用户读取所有消息不显示未读标志，否则显示
                    mUnReadTag.setVisibility(View.GONE);
                } else {
                    int unReadCount = myMessageBeanList.size() - userReadMessageBeanList.size();
                    mUnReadTag.setVisibility(View.VISIBLE);
                    mUnReadTag.setText(unReadCount + "");
                }
            } else {
                mUnReadTag.setVisibility(View.VISIBLE);
                mUnReadTag.setText(myMessageBeanList.size() + "");
            }
        } else {
            mUnReadTag.setVisibility(View.GONE);
        }
    }
}
